import {
  HttpException,
  HttpStatus,
  Injectable,
  ServiceUnavailableException,
} from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateCategoryDto } from '../dto/category/create-category.dto';
import { UpdateCategoryDto } from '../dto/category/update-category.dto';
import { Category } from '../entities/category.entity';
import { ResMsg } from 'src/utils/public.enum';
import { ListCategoryDto } from '../dto/category/list-category.dto';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(Category, 'shop')
    private readonly categoryRepository: Repository<Category>,
  ) {}

  async create(createCategoryDto: CreateCategoryDto) {
    try {
      const row = new Category(createCategoryDto);
      const result = await this.categoryRepository.save(row);
      if (result) {
        return ResMsg.Success;
      }
      return ResMsg.Fail;
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async findAll(listCategoryDto: ListCategoryDto) {
    try {
      const { id = null, title = '', remark = '' } = listCategoryDto.queryDto;
      const queryBuilder =
        this.categoryRepository.createQueryBuilder('category');

      if (id) {
        queryBuilder.where('category.id = :id', { id });
      }

      queryBuilder
        .andWhere('category.is_delete = :is_delete', { is_delete: 1 })
        .andWhere(
          'category.title LIKE :title AND category.remark LIKE :remark',
          { title: `%${title}%`, remark: `%${remark}%` },
        );

      const [list, total] = await queryBuilder
        .orderBy('category.order', 'DESC')
        .skip(
          (listCategoryDto.pageDto.pageNo - 1) *
            listCategoryDto.pageDto.pageSize,
        )
        .take(listCategoryDto.pageDto.pageSize)
        .getManyAndCount();

      return {
        list,
        total,
        ...listCategoryDto.pageDto,
      };
    } catch (e) {
      throw new ServiceUnavailableException(e);
    }
  }

  async findOne(id: number) {
    try {
      const res = await this.categoryRepository.findOneBy({ id, isDelete: 1 });

      return res;
    } catch (e) {
      throw new ServiceUnavailableException(e);
    }
  }

  async update(id: number, updateCategoryDto: UpdateCategoryDto) {
    try {
      const dbRow = await this.findOne(id);
      if (dbRow) {
        const data = {
          ...dbRow,
          ...updateCategoryDto,
        };
        const result = this.categoryRepository.save(data);
        if (result) {
          return ResMsg.Success;
        }
        return ResMsg.Fail;
      } else {
        throw new HttpException('当前数据不存在！', HttpStatus.BAD_REQUEST);
      }
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async remove(id: number) {
    try {
      const dbRow = await this.findOne(id);
      if (dbRow) {
        const data = {
          ...dbRow,
          isDelete: -1,
        };
        const result = this.categoryRepository.save(data);
        if (result) {
          return ResMsg.Success;
        }
        return ResMsg.Fail;
      } else {
        throw new HttpException('当前数据不存在！', HttpStatus.BAD_REQUEST);
      }
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }
}
